import { createRouter, createWebHistory } from "vue-router";
import Home from '../views/Home.vue'
import Registion from '../views/Registion.vue'
// 占位页面组件
const Charge = () => import('../views/Charge.vue')
const UserManage = () => import('../views/UserManage.vue')
const ECard = () => import('../views/ECard.vue')
const Retire = () => import('../views/Retire.vue')
const DoctorSchedule = () => import('../views/DoctorSchedule.vue') // 医生排班
const Notice = () => import('../views/Notice.vue') // 系统公告
const Settle = () => import('../views/Settle.vue') // 患者结算

const webHistory = createWebHistory();

// 路由数组，每个菜单项对应一个页面
const routes = [
  {
    path: "/login",
    name: "Login",
    component: Registion
  },
  {
    path: "/",
    name: "Home",
    component: Home
  },
  {
    path: "/charge",
    name: "Charge",
    component: Charge
  },
  {
    path: "/user-manage",
    name: "UserManage",
    component: UserManage
  },
  {
    path: "/ecard",
    name: "ECard",
    component: ECard
  },
  {
    path: "/onsite",
    name: "Onsite",
    component: Home // 现场挂号页面，复用Home.vue
  },
  {
    path: "/retire",
    name: "Retire",
    component: Retire
  },
  {
    path: "/doctor-schedule",
    name: "DoctorSchedule",
    component: DoctorSchedule
  },
  {
    path: "/notice",
    name: "Notice",
    component: Notice
  },
  {
    path: "/settle",
    name: "Settle",
    component: Settle
  }
];

const router = createRouter({
  // 配置路由模式
  history: webHistory,
  // 配置路由
  routes,
});

// 路由守卫：未登录只能访问登录页，已登录不能访问登录页
router.beforeEach((to, from, next) => {
  // 从localStorage获取登录状态
  const isLogin = localStorage.getItem('isLogin') === 'true';
  // 未登录时，访问非登录页强制跳转到登录页
  if (to.path !== '/login' && !isLogin) {
    next('/login');
  // 已登录时，访问登录页自动跳转到主页
  } else if (to.path === '/login' && isLogin) {
    next('/');
  } else {
    next();
  }
});

export default router;